<?php
/**
 * Created by PhpStorm.
 * User: hans
 * Date: 16/6/13
 * Time: 上午11:02.
 */
namespace App\Http\Controllers;

use Dingo\Api\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;

/**
 * Class CaptchaController.
 * 图形验证码
 */
class CaptchaController extends BaseController
{
    /**
     * 获取图形验证码
     *
     * //no test
     *
     * @Get("/captcha")
     * @Parameters({
     *     @Parameter("cid", description="验证码ID")
     * })
     *
     * @Transaction({
     *     @Request({"cid":"the-unique-id-for-captcha"}),
     *     @Response(200, body={"captcha_id":"the-unique-id-for-captcha", "img_url":"http://img/url"}),
     *     @Request({}),
     *     @Response(200, contentType="image/jpeg")
     * })
     *
     * @param Request $request
     *
     * @return mixed4
     */
    public function getCaptcha(Request $request)
    {
        $cid = $request->input('cid');

        //Return img
        if ($cid) {
            $phrase = app('redis')->get('captcha:'.$cid);

            $builder = new CaptchaBuilder();
            $builder->setPhrase($phrase);
            $builder->build(80, 25);

            header('Content-type: image/jpeg');
            $builder->output();

            return;
        }

        //Return img url
        $phrase = $this->buildCaptchaPhrase(4);
        $captchaId = $this->storeCaptcha($phrase);

        return $this->response->array(['captcha_id' => $captchaId, 'img_url' => url('captcha').'?cid='.$captchaId]);
    }

    /**
     * 生成验证码内容.
     *
     * @param int $length
     * @param int $type
     *
     * @return string
     */
    protected function buildCaptchaPhrase($length = 5, $type = 0)
    {
        $numbers = '23456789';
        $charsLower = 'abcdefghjkmnpqrstuvwxyz';
        $charsUpper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';

        $length = min($length, 8); //max length 8
        $length = max($length, 1); //min length 1

        if ($type == 0) { //numbers only
            $charset = $numbers;
        } elseif ($type == 1) { //letters only
            $charset = $charsLower.$charsUpper;
        } elseif ($type == 2) { //numbers & letters
            $charset = $charsLower.$charsUpper.$numbers;
        }

        $phrase = '';
        $chars = str_split($charset);

        for ($i = 0; $i < $length; ++$i) {
            $phrase .= $chars[array_rand($chars)];
        }

        return $phrase;
    }

    /**
     * 存储Captcha.
     *
     * //no test
     *
     * @param $phrase
     *
     * @return string
     */
    protected function storeCaptcha($phrase)
    {
        $cid = md5(uniqid().rand(100000, 999999));
        app('redis')->setex('captcha:'.$cid, 60, $phrase);

        return $cid;
    }
}
